package cn.glccc.common.exception;

import cn.glccc.common.vo.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/*
 * 全局异常处理器
 *
 * @author glccc
 * @date 2024-06-08
 */
@Slf4j
@RestControllerAdvice
@Order(10)
public class GlobalExceptionHandler {

    /*
     * 参数缺失异常
     */
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<?> handleMissingServletRequestParameterException(MissingServletRequestParameterException e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}'，发生参数缺失异常：{}", requestURI, e.getMessage());
        return Result.failure("参数缺失：" + e.getMessage());
    }

    /*
     * 未知的运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    public Result<?> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        e.printStackTrace();
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}'，发生未知异常：{}", requestURI, e.getMessage());
        return Result.failure("未知异常：" + e.getMessage());
    }

    /*
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public Result<?> handleException(Exception e, HttpServletRequest request) {
        e.printStackTrace();
        String requestURI = request.getRequestURI();
        log.error("请求地址'{}'，发生系统异常：{}", requestURI, e.getMessage());
        return Result.failure("系统异常：" + e.getMessage());
    }

}
